import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/stroage'

// 路由懒加载
const login = () => import('@/views/login/index.vue')
const layout = () => import('@/views/layout')
const home = () => import('@/views/home/index')
const addArticle = () => import('@/views/layout/components/add-article.vue')
const articles = () => import('@/views/layout/components/articles.vue')
const comments = () => import('@/views/layout/components/comments.vue')
const fans = () => import('@/views/layout/components/fans.vue')
const pictures = () => import('@/views/layout/components/pictures.vue')
const settings = () => import('@/views/layout/components/settings.vue')
const NotFound404 = () => import('@/views/NotFound')

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: layout,
    children: [
      {
        path: '', // path为空 会作为默认子路由渲染
        name: 'home',
        component: home
      },
      {
        path: '/addArticle/:id?',
        name: 'addArticle',
        component: addArticle
      },
      {
        path: '/articles',
        name: 'articles',
        component: articles
      },
      {
        path: '/comments',
        name: 'comments',
        component: comments
      },
      {
        path: '/fans',
        name: 'fans',
        component: fans
      },
      {
        path: '/pictures',
        name: 'pictures',
        component: pictures
      },
      {
        path: '/settings',
        name: 'settings',
        component: settings
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: login
  },
  {
    // * 表示匹配所有路径，用于放最后配置 404
    path: '*',
    name: '404',
    component: NotFound404
  }
]

const router = new VueRouter({
  routes
})

// 配置路由的导航守卫
// beforeEach提供的函数会在所有的路由发生跳转之前。
// next() 如果直接调用 next() 代表放行  next('/login') 代表跳转到login
// 1 如果有token，或者直接取登录 就直接放行
// 2 否则就拦截到登录去
router.beforeEach((to, from, next) => {
  const token = getToken()
  if (to.path === '/login' || token) {
    next()
  } else {
    next('/login')
  }
})

export default router
